import TodoDom from "./TodoDom";
import { addTodo, getTodoList, removeTodo, toggleTodo } from "./TodoService";
import { ITodoData } from "./typing";

class TodoEvent extends TodoDom{

    private todoData: ITodoData[];
    private todoDom: HTMLElement;

    constructor (todoData: ITodoData[], todoDom: HTMLElement) {
        super(todoDom);
        this.todoData = todoData;
        this.init(this.todoData);
    }

    @getTodoList
    private init (todoData: ITodoData[]) {
        this.todoData = todoData;
        this.initList(this.todoData);
    }

    @addTodo
    public addTodo (todo: ITodoData): undefined | number {
        const _todo: null | ITodoData = this.todoData.find(item => item.content === todo.content);
        
        if(!_todo) {
           this.todoData.push(todo);
            // TodoDom操作视图
           this.addItem(todo);
           return;
        }

        return 1001;
    }

    @removeTodo
    public removeTodo (target: HTMLElement, id: number): void {
        this.todoData = this.todoData.filter((todo: ITodoData) => todo.id !== id);
        // TodoDom操作视图
        this.removeItem(target);
    }

    @toggleTodo
    public toggleCompleted (target: HTMLElement, id: number): void {
        this.todoData = this.todoData.map((todo: ITodoData) => {
            if(todo.id === id) {
                todo.completed = !todo.completed
                // TodoDom操作视图
                this.changeCompleted(target, todo.completed);
            }
            return todo;
        })
    }

}

export default TodoEvent;